package cn.haoxsf.app.system.dto;

import cn.haoxsf.app.system.entity.Member;
import cn.haoxsf.app.system.entity.Permission;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: app
 * @description: SpringSecurity需要的用户详情
 * @author: Ele qvbanfm@qq.com
 * @create: 2020-01-06 13:13
 **/
@Data
public class LoginUser implements UserDetails {
    @JsonIgnore
    private Long id;
    private String username;
    private String password;
    private String nickname;
    private String openId;
    @JsonIgnore
    private boolean enabled = true;

    private List<Permission> permissionList;

    public LoginUser() {
    }

    public LoginUser(Member member, List<Permission> permissionList) {//
        this.username = member.getUsername();
        this.password = member.getPassword();
        this.nickname = member.getNickName();
        this.openId = member.getOpenId();
        if (!"ENABLE".equals(member.getStatus())) {
            this.enabled = false;
        }
        this.permissionList = permissionList;
        this.id = member.getId();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //返回当前用户的权限
        return permissionList.stream()
                .filter(permission -> permission.getValue() != null)
                .map(permission -> new SimpleGrantedAuthority(permission.getValue()))
                .collect(Collectors.toList());
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
}
